/**
 * 
 */
package com.${ltdAbbr}.xiao.${module}.task.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @author admin
 *
 */
@Component("loginCheckInterceptor")
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {

    public static final String SESSION_KEY = "login_user";

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String contextPath = request.getContextPath();
        if(StringUtils.startsWith(request.getRequestURI(), (contextPath.length()>0?contextPath:"")+"/site/")) {
            return true;
        }
        if(request.getSession().getAttribute(SESSION_KEY)!=null) {
            return true;
        }
        if(StringUtils.equalsIgnoreCase(request.getHeader("X-Requested-With"), "XMLHttpRequest")){
            response.setStatus(401);
        }else{
            //request.getRequestDispatcher(loginUrl).forward(request, response);
            response.sendRedirect("/site/login.action");
        }
        return false;
    }

}
